package cn.crism.chatme.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @Description: 用于检测channel的心跳handler 
 * 				 继承ChannelInboundHandlerAdapter，从而不需要实现channelRead0方法
 */
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

	public static ChannelGroup users = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		/* 用于触发用户事件 读/写/读写空闲 */
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent event = (IdleStateEvent) evt;
			/* 读 写 读写 空闲 */
			if (event.state() == IdleState.READER_IDLE){
//				System.out.println("读空闲");
			} else if (event.state() == IdleState.WRITER_IDLE){
//				System.out.println("写空闲");
			} else if (event.state() == IdleState.ALL_IDLE){
//				System.out.println("读写空闲");
				Channel channel = ctx.channel();
				/* 关闭不用读channel资源 */
				channel.close();
				System.out.println("当前在线用户数量: "+ users.size());
			}
		}
	}
}
